from io import BytesIO

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.modelforms.acount import RegisterModelform, SendSmsForm, LoginSMSForm, LoginPasswordForm
from utils.image_code import check_code
from utils.order_code import order_code


# 注册
def register(request):
    if request.method == 'GET':
        # 生成表单
        form = RegisterModelform()
        return render(request, "app01/register.html", {"form": form})
    # 校验字段
    form = RegisterModelform(data=request.POST)
    if form.is_valid():
        # 验证码通过，提交数据(写入数据库，密码密文)
        form.save()
        mobile_phone = form.cleaned_data.get('mobile_phone', 0)
        user_id = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first().id
        models.UransactionRecord.objects.create(state='已支付', user_id=user_id, order_code=order_code())
        return JsonResponse({'status': True, 'data': '/app01/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 发送短信验证码
def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 短信登录
def login_sms(request):
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'app01/login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        user_object = form.cleaned_data.get('mobile_phone')
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 15)
        # return redirect('http://127.0.0.1:8000/app01/index/')
        return JsonResponse({"status": True, "data": "/app01/index/"})
    return JsonResponse({"status": False, "error": form.errors})


# 密码登录
def login(request):
    if request.method == "GET":
        form = LoginPasswordForm(request)
        return render(request, "app01/login.html", {'form': form})
    form = LoginPasswordForm(request, data=request.POST)
    if form.is_valid():
        # return JsonResponse({"status": True, "data": "/app01/register/"})
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('mobile_password')
        # user_object = models.UserInfo.objects.filter(mobile_phone=username, password=password).first()
        from django.db.models import Q
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 15)
            return redirect('http://127.0.0.1:8000/app01/index/')
        form.add_error('username', '用户或密码输入错误！')
        form.add_error('mobile_password', '用户或密码输入错误！')
    return render(request, 'app01/login.html', {'form': form})


# 生成图片验证码
def image_code(request):
    img, code = check_code()

    request.session['image_code'] = code  # 将图片验证码加入session(默认过期时间：2周)
    request.session.set_expiry(60)  # 手动设置session过期时间60秒

    stream = BytesIO()
    img.save(stream, 'png')  # 将图片验证码写入内存
    return HttpResponse(stream.getvalue())


# 首页
def index(request):
    return render(request, 'app01/index.html')


# 退出
def logout(request):
    request.session.flush()
    return redirect('http://127.0.0.1:8000/app01/index/')


# 项目管理
def project_index(request):
    user_id = request.session.get('user_id')
    if request.method == "POST":
        project = dict(request.POST)
        if not project['project_name']:
            return JsonResponse({"status": False, "error": '项目名称不能为空！'})
        project_ob = models.ProjectInformation.objects.filter(created_by=user_id,
                                                              project_name=project['project_name'][0]).first()
        if not project_ob:
            models.ProjectInformation.objects.create(project_name=project['project_name'][0],
                                                     describe=project['project_text'][0],
                                                     color=project['project_color'][0],
                                                     star_labe='False', project_in_member_qty=1, created_by=user_id,
                                                     used_space=0)
            return JsonResponse({"status": True, "data": "/app01/project_index/"})
        return JsonResponse({"status": False, "error": '项目名已存在！'})
    project_ob = models.ProjectInformation.objects.raw(
        'SELECT t1.id,t1.project_name,t1.DESCRIBE,t1.color,t1.star_labe,t1.project_in_member_qty,t1.created_by,t1.used_space,t2.NAME,t2.email,t2.mobile_phone FROM app01_projectinformation t1 LEFT JOIN app01_userinfo t2 ON t1.created_by = t2.id where t1.created_by = %s',
        [user_id])
    # count_false = models.ProjectInformation.objects.filter(created_by=user_id, star_labe='False').count()
    # count_true = models.ProjectInformation.objects.filter(created_by=user_id, star_labe='True').count()
    return render(request, "app01/project_index.html", {"form": project_ob})


# , "count_false": count_false, 'count_true': count_true}


# 标星
def starlabel(request):
    if request.method == 'POST':
        project_name = dict(request.POST)['project_name'][0]
        user_id = request.session.get('user_id')
        print(project_name, user_id, dict(request.POST)['label'][0])
        if dict(request.POST)['label'][0] == "True":
            models.ProjectInformation.objects.filter(project_name=project_name, created_by=user_id).update(
                star_labe='True')
        else:
            models.ProjectInformation.objects.filter(project_name=project_name, created_by=user_id).update(
                star_labe='False')
    return render(request, "app01/project_index.html", {'data': 'app01/project_index/'})
